import 'dart:math';

import 'package:cave_flutter/style/whl_style.dart';
import 'package:cave_flutter/utils/whl_current_limiting_util.dart';
import 'package:cave_flutter/widgets/TextSpanField/special_text/whl_special_text_span_builder.dart';
import 'package:cave_flutter/widgets/brick/brick.dart';
import 'package:cave_flutter/widgets/brick/widget/basic_widget.dart';
import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:extended_text_field/extended_text_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import 'whl_bottom_control_view_logic.dart';

class WhlBottomControlViewPage extends StatefulWidget {
  // final RCIMIWConversation conversationModel;
  bool? isShowKeyBoard = true;
  String? toAccountId = '';
  bool? isGroup;
  int? caveId = 0;
  WhlBottomControlViewPage({Key? key, this.isGroup,this.isShowKeyBoard,this.toAccountId,this.caveId}) : super(key: key);

  @override
  State<WhlBottomControlViewPage> createState() =>
      _WhlBottomControlViewPageState();
}

class _WhlBottomControlViewPageState extends State<WhlBottomControlViewPage> {
  late WhlBottomControlViewLogic logic;

  @override
  void dispose() {
    // Get.delete<BottomControlViewLogic>();
    super.dispose();
    // Get.delete<BottomControlViewLogic>();
  }

  @override
  void initState() {
    super.initState();
    logic = Get.put(
      WhlBottomControlViewLogic(),
    );
    logic.isGroup = widget.isGroup ?? false;
    logic.caveId = widget.caveId ?? 0;
    logic.toAccountId = widget.toAccountId ?? '';

  }

  @override
  Widget build(BuildContext context) {

    logic = Get.put(
      WhlBottomControlViewLogic(),
    );
    logic.toAccountId = widget.toAccountId??"";
    return SafeArea(
      top: false,
      child: UIColumn(
        decoration: BoxDecoration(color: Colors.white),
        children: [
          IntrinsicHeight(
            child: UIRow(
              margin: EdgeInsets.symmetric(vertical: 13.h),
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                UIImage(
                  assetImage: 'icon_chat_record.png',
                  width: 28.w,
                  margin: EdgeInsets.only(left: 8.w),
                  onTap: () {
                    logic.doClickVoiceRecord();
                  },
                ),
                Expanded(
                  child: UIContainer(
                    color: kAppColor('#F4F5F8'),
                    margin: EdgeInsets.only(right: 8.w, left: 5.w),
                    padding: EdgeInsets.only(left: 12.w, right: 5.w),
                    radius: 20.w,
                    // height: 44.h,
                    child: GetBuilder<WhlBottomControlViewLogic>(
                      builder: (logic) {
                        // if (logic.isShowVoice) {
                        //   return buildVoiceWidget();
                        // } else {
                        return buildInputWidget(context);
                        // }
                      },
                    ),
                  ),
                ),
                UIImage(
                  margin: EdgeInsets.only(right: 5.w),
                  assetImage: 'icon_chat_gift.png',
                  width: 30.w,
                  onTap: () {
                    logic.doClickEmoji();
                  },
                ),
                UIImage(
                  margin: EdgeInsets.only(right: 5.w),
                  assetImage: 'icon_chat_emoji.png',
                  width: 30.w,
                  onTap: () {
                    logic.doClickEmoji();
                  },
                ),
                UIImage(
                  margin: EdgeInsets.only(right: 9.w),
                  assetImage: 'icon_chat_more.png',
                  width: 30.w,
                  onTap: () {
                    logic.doClickMore();
                  },
                )
              ],
            ),
          ),
          GetBuilder<WhlBottomControlViewLogic>(
            builder: (logic) {
              return Visibility(
                visible: logic.isShowEmoji,
                child: SizedBox(
                  height: 200.h,
                  child: Stack(
                    alignment: Alignment.bottomRight,
                    children: [
                      EmojiPicker(
                        onEmojiSelected: (category, emoji) {
                          logic.inputTextController.text =
                              logic.inputTextController.text + emoji.emoji;
                        },
                        onBackspacePressed: () {
                          if (logic.inputTextController.text.isEmpty) return;
                          WhlCurrentLimitingUtil.debounce(() {
                            logic.inputTextController.text =
                                logic.inputTextController.text.substring(
                                    0,
                                    min(
                                        logic.inputTextController.text.length -
                                            2,
                                        logic.inputTextController.text.length -
                                            1));
                          });
                        },
                        config: Config(
                            columns: 7,
                            emojiSizeMax: 25.w,
                            verticalSpacing: 0,
                            horizontalSpacing: 0,
                            initCategory: Category.RECENT,
                            bgColor: kAppColor('#FDFDFD'),
                            indicatorColor: Colors.blue,
                            iconColor: Colors.grey,
                            iconColorSelected: Colors.blue,
                            recentsLimit: 28,
                            categoryIcons: const CategoryIcons(),
                            buttonMode: ButtonMode.MATERIAL),
                      ),
                      UIText(
                        margin: EdgeInsets.only(bottom: 20.h, right: 20.w),
                        text: 'Send',
                        fontSize: 16.sp,
                        textColor: Colors.white,
                        alignment: Alignment.center,
                        width: 60.w,
                        height: 30.h,
                        radius: 4.w,
                        gradientStartColor: kAppLeftColor,
                        gradientEndColor: kAppRightColor,
                        onTap: () {
                          // FocusScope.of(context).requestFocus(logic.focusNode);
                          logic.doClickSend(logic.inputTextController.text);
                        },
                      )
                    ],
                  ),
                ),
              );
            },
          ),
          GetBuilder<WhlBottomControlViewLogic>(
            builder: (logic) {
              return Visibility(
                visible: logic.isShowMore,
                child: Container(
                  color: kAppColor('#FDFDFD'),
                  child: GridView.builder(
                    padding: EdgeInsets.zero,
                    shrinkWrap: true,
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 4),
                    itemBuilder: (context, index) {
                      ButtonModel model = logic.gridItemList[index];
                      return UIText(
                        alignment: Alignment.center,
                        text: model.title,
                        fontSize: 13.sp,
                        textColor: kAppColor('#979797'),
                        marginDrawable: 6.h,
                        topDrawable: UIImage(
                          assetImage: model.icon,
                          width: 49.w,
                        ),
                        onTap: () {
                          logic.doClickFunctionBtn(model);
                        },
                      );
                    },
                    itemCount: logic.gridItemList.length,
                  ),
                ),
              );
            },
          )
        ],
      ),
    );
  }

  buildInputWidget(context) {
    return
        // widget.isShowKeyBoard == true
        //   ?
        ExtendedTextField(
      controller: logic.inputTextController,
      textAlign: TextAlign.left,
      focusNode: logic.focusNode,
      textCapitalization: TextCapitalization.sentences,
      specialTextSpanBuilder: WhlSpecialTextSpanBuilder(
        showAtBackground: false,
      ),
      enabled: true,
      decoration: InputDecoration(
        hintText: '输入消息…',
        hintStyle: TextStyle(color: kAppColor('#CCCCCC'), fontSize: 14.sp),
        border: const OutlineInputBorder(borderSide: BorderSide.none),
        contentPadding: const EdgeInsets.all(5),
      ),
      style: TextStyle(fontSize: 15.sp, color: kAppTextColor),
      textInputAction: TextInputAction.send,
      // maxLines: 5,
      minLines: 1,
      onTap: () {
        logic.isShowEmoji = false;
        logic.isShowMore = false;
        logic.isShowVoice = false;
        logic.update();
      },
      // keyboardType: TextInputType.multiline,
      onSubmitted: (value) {
        // FocusScope.of(context).requestFocus(logic.focusNode);
        logic.doClickSend(value);
      },
    );
    // : UIClick(
    // child: Container(color: Colors.transparent),
    // onTap: () {
    //   FocusScope.of(context).requestFocus(logic.focusNode);
    //   logic.roomLogic.onScrollToBottom();
    //   logic.isShowEmoji = false;
    //   logic.isShowMore = false;
    //   logic.update();
    // });
  }

  buildVoiceWidget() {
    return UIText(
      color: Colors.white,
      text: "按住说话",
      fontSize: 15.sp,
      textColor: kAppTextColor,
      alignment: Alignment.center,
      radius: 4.w,
      padding: EdgeInsets.symmetric(vertical: 10.w),
      onLongPress: () {
        print("long press");
        // logic.startRecording();
      },
      onLongPressEnd: (e) {
        print("cancel");
        // logic.stopRecording();
      },
      // onLongPressMoveUpdate: (e) {
      //   bool oldMove = logic.logic.isMoveOut;
      //   if (e.localPosition.dy < -30) {
      //     logic.logic.isMoveOut = true;
      //   } else {
      //     logic.logic.isMoveOut = false;
      //   }
      //   if (oldMove != logic.logic.isMoveOut) {
      //     logic.logic.update(['audioRecord']);
      //   }
      // },
    );
  }
}
